package com.itljm.cxrMarket.controller;

import com.itljm.cxrMarket.common.BusinessException;
import com.itljm.cxrMarket.common.Result;
import com.itljm.cxrMarket.utils.JwtUtil;
import com.itljm.cxrMarket.utils.RedisUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ljm
 * @date 2024/11/29 11:07
 */
@RestController
@RequestMapping("/jwt")
@CrossOrigin
public class JwtController {
    @Autowired
    private JwtUtil jwtUtil;
    @Autowired
    private RedisUtil redisUtil;

    @RequestMapping("/refreshToken")
    public Result refreshToken(HttpServletRequest request) {
        // 获取刷新令牌
        String token = request.getHeader("RefreshToken");
        String userId;
        // 验证刷新令牌是否过期，如果过期就重新登录
        if (!jwtUtil.validateToken(token)){
            return Result.fail(501,"token已过期，请重新登录");
        }
        try {
            Claims claims = jwtUtil.parseJWT(token);
            userId = claims.getSubject();
        } catch (Exception e) {
            throw new BusinessException("token非法，请重新登陆");
        }
        // 刷新用户信息的过期时间
        redisUtil.expire("user:"+userId,3, TimeUnit.DAYS);

        Map<String,Object> map = new HashMap();
        map.put("AccessToken",jwtUtil.generateAccessToken(userId));

        return Result.ok(map);
    }
}
